<?php
/**
 * Created by PhpStorm.
 * User: lizx
 * Date: 2018/1/31
 * Time: 9:17
 */

namespace app\api\controller\v1;

use app\api\controller\Fun;
use app\api\repository\UserRepository;
use app\api\repository\UserBalanceRespository;
use app\common\Model\Freight;
use app\common\Model\Region;
use app\common\Model\User;
use app\common\Model\UserAddress;
use app\common\Model\UserShaohuo;
use app\common\Server\Validate;
use think\Config;
use think\Db;
use think\exception\ErrorException;

/**
 * @title 用户类接口V1
 * @description 接口说明
 *
 * @header name:copyright require:1 default:v1 desc:版本号(全局)
 */
class UserInfo extends Auth
{
    static public $validate = [
        'addOrUpdateAddress' => [
            'base' => [
                'operate_type' => 'operate_type'
            ],
            'status' => [
                [
                    'key' => ['operate_type'],
                    'value' => [
                        [
                            'rule' => [
                                'operate_type' => 'add'
                            ],
                            'valid' => [
                                'uid' => 'uid',
                                'consignee' => 'consignee',
                                'address' => 'address',
                                'mobile' => 'mobile',
                                'lat' => 'lat',
                                'lng' => 'lng',
                            ]
                        ],
                        [
                            'rule' => [
                                'operate_type' => 'update'
                            ],
                            'valid' => [
                                'uid' => 'uid',
                                'address_id' => 'address_id',
                                'lat' => 'lat',
                                'lng' => 'lng',
                            ]
                        ]
                    ]
                ]
            ]
        ],
        'getUserAddress' => [
            'base' => [
                'uid' => 'uid',
            ]
        ],
        'updateUserInfo' => [
            'base' => [
                'uid' => 'uid'
            ]
        ],
        'deleteAddress' => [
            'base' => [
                'uid' => 'uid',
                'address_id' => 'address_id'
            ]
        ]
    ];


    /**
     * @title 用户信息
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:userInfo desc:用户信息
     * @param name:uid type:interval require:1 default: other: desc:用户id
     * @param name:token type:interval require:1 default: other: desc:用户token
     *
     * @return data:[]
     */
    public function userInfo()
    {
        if (!($uid = $this->arr['uid'] ?? 0)) {
            return Fun::error('999993');
        }

        $user = UserRepository::instance()->userInfo($uid);
        if ($user) {

            if(!empty($this->arr['app_name']) && $this->arr['app_name'] == 'shr'){
                $user['is_shr'] = '0';
                if(UserShaohuo::get(['uid' => $uid,'status' => 1])) $user['is_shr'] = '1';
            }

            return Fun::success($user);
        } else {
            return Fun::error('100000');
        }
    }

    /**
     * @title 修改用户信息
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:updateUserInfo desc:修改用户信息
     * @param name:uid type:interval require:1 default: other: desc:用户id
     * @param name:token type:interval require:1 default: other: desc:用户token
     * @param name:sex type:interval require:0 default: other: desc:性别0未设置1男2女
     * @param name:real_name type:interval require:0 default: other: desc:真实姓名
     * @param name:nick_name type:interval require:0 default: other: desc:昵称
     * @param name:birthday type:interval require:0 default: other: desc:生日时间戳
     * @param name:header_img type:interval require:0 default: other: desc:头像
     * @param name:signature type:interval require:0 default: other: desc:签名
     *
     * @return data:[]
     */
    public function updateUserInfo()
    {
        extract($this->arr);

        //允许修改字段
        $allow = ['sex', 'real_name', 'nick_name', 'birthday', 'header_img', 'signature'];

        //组织数据
        $data = [];
        foreach ($allow as $key) {
            if($key == 'sex' && isset($$key)){
                $data['sex'] = intval($$key);
            }
            if ($$key ?? '') {
                //处理个别数据
                if ($key == 'birthday') {
                    $$key = date('Y-m-d', strtotime($$key));
                }
                $data[$key] = $$key;
            }
        }

        //字段值不变化视为修改成功
        Db::startTrans();
        try {
            $address_model = new User();
            $address_model->save(
                $data, [
                    'uid' => $uid,
                ]
            );

            $user = UserRepository::instance()->userInfo($uid);
            Db::commit();
            return Fun::success($user, '修改成功');
        } catch (ErrorException $exception) {
            Db::rollback();
            return Fun::error('801010');
        }
    }

    /**
     * @title 添加或更新地址
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:addOrUpdateAddress desc:添加或更新地址
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:operate_type type:interval require:1 default: other: desc:类型update|add
     * @param name:uid type:string require:0 default: other: desc:用户id
     * @param name:consignee type:string require:0 default: other: desc:收获人姓名
     * @param name:address type:string require:0 default: other: desc:地址
     * @param name:building type:string require:0 default: other: desc:门牌号
     * @param name:is_default type:string require:0 default: other: desc:是否默认 1 是 0 否
     * @param name:mobile type:string require:0 default: other: desc:手机号
     * @param name:lat type:interval require:0 default: other: desc:经度
     * @param name:lng type:interval require:0 default: other: desc:纬度
     * @param name:address_id type:interval require:0 default: other: desc:地址id
     * @param name:type type:interval require:0 default: other: desc:地址类型|1收货地址|2发货地址|3服务地址
     * @param name:source type:interval require:0 default: other: desc:地址类型|1捎货|2宅配|3云商
     *
     * @return data:[]
     */
    public function addOrUpdateAddress()
    {
        extract($this->arr);
        //验证手机号
        if ($this->arr['mobile'] ?? '') {
            $mobile = Validate::instance()->getPhone($this->arr['mobile']);
            if (!$mobile) {
                return Fun::error('801004');
            }
        }

        //根据经纬度检查区域是否在业务范围，获取省市区id
        $ak = Config::get('baidu_map.ak');
        $str = 'http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=' . $lat . ',' . $lng . '&output=json&pois=1&pois=0&ak=';
        $rtn = file_get_contents($str . $ak);

        $info = str_replace('renderReverse&&renderReverse(', '', $rtn);
        $info = str_replace(')', '', $info);

        $info = json_decode($info);

        if (empty($district_id = $info->result->addressComponent->adcode ?? '')) {
            return Fun::error('801016');
        }

        $district = Region::get($district_id);
//        if (!($district->is_open ?? 0)) {
            //区域未开通
//            return Fun::error('801015');
//        }
        $city = Region::get($district->parent_id);

        //前后端统一
        $is_open = Freight::get(['city_region_id' => $city->region_id,'is_del' => 0]);
        if (!$is_open) {
        //区域未开通
            return Fun::error('801015');
        }

        $province = Region::get($city->parent_id);
        $city = $city->name;
        $province = $province->name;
        $district = $district->name;

        //匹配删除省市区信息
        $address = preg_replace("/^.*$district/", '', $address ?? '');

        $is_default = intval($this->arr['is_default'] ?? 0);

        Db::startTrans();
        try {
            //处理新增的数据
            $data = array(
                'uid' => $uid,
                'consignee' => $consignee ?? '',
                'mobile' => $mobile ?? '',
                'province' => $province ?? 0,
                'city' => $city ?? 0,
                'district' => $district ?? 0,
                'address' => $address ?? '',
                'building' => $building ?? '',
                'is_default' => $is_default,
                'lat' => $lat ?? '',
                'lng' => $lng ?? '',
                'type' => $type ?? 0,
                'source' => $source ?? 0
            );

            //判断是否为默认地址
            if ($is_default) {
                //取消该分类下以往默认地址
                UserAddress::update([
                    'is_default' => 0
                ], [
                    'uid' => $uid,
                    'type' => $type ?? 0
                ]);
            }

            //判断是否更新
            if ($operate_type != 'update') {
                UserAddress::create($data);
            } else {
                //删除空数据
                foreach ($data as $key => $value) {
                    if (!$value) {
                        if($key == 'is_default' && isset($this->arr['is_default']))continue;//补丁,取消默认地址
                        unset($data[$key]);
                    }
                }
                unset($data['uid']);
                $address_model = new UserAddress();
                $address_model->save(
                    $data, [
                        'id' => $address_id,
                        'uid' => $uid,
                    ]
                );
//                Address::update([
//                    'id' => $address_id,
//                ],$data);
            }

            Db::commit();

            if ($operate_type == 'add') {
                $str = '添加成功';
            } else {
                $str = '修改成功';
            }

            return Fun::success([], $str);
        } catch (ErrorException $exception) {
            Db::rollback();
            return Fun::error('');
        }
    }

    /**
     * @title 删除地址
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:deleteAddress desc:删除地址
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other: desc:用户id
     * @param name:address_id type:interval require:1 default: other: desc:地址id
     *
     * @return data:[]
     */
    public function deleteAddress()
    {
        $rtn = UserAddress::where(['uid' => $this->arr['uid'], 'id' => $this->arr['address_id']])
            ->update(['is_delete' => 1]);
        if ($rtn) {
            return Fun::success([], '删除成功');
        } else {
            return Fun::error('801017');
        }
    }

    /**
     * @title 用户地址列表
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:getUserAddress desc:用户地址列表
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other: desc:用户id
     * @param name:current_page type:string require:0 default:1 other: desc:当前页
     * @param name:per_page type:string require:0 default:10 other: desc:每页大小
     * @param name:type type:interval require:0 default: other: desc:地址类型|1收货地址|2发货地址|3服务地址
     * @param name:source type:interval require:0 default: other: desc:地址类型|1捎货|2宅配|3云商
     *
     * @return data:[]
     */
    public function getUserAddress()
    {
        extract($this->arr);

        //组织查询条件
        $data['uid'] = $uid;
        $data['is_delete'] = 0;
        if ($type = $type ?? 0) {
            $data['type'] = $type;
        }

        if ($source = $source ?? 0) {
            $data['source'] = $source;
        }

        $current_page = $current_page ?? 1;
        $per_page = $per_page ?? 10;
        //组织分页信息
        $paginate = [
            'page' => $current_page,
        ];

        //查询数据
        $info = UserAddress::where($data)->order('is_default desc,id desc')->paginate(intval($per_page), false, $paginate)->toArray();

        return Fun::success($info);
    }

    /**
     * @title 用户优惠券列表
     * @description
     * @author lizx
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:getUserVoucher desc:用户优惠券列表
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other: desc:用户id
     * @param name:current_page type:string require:0 default:1 other: desc:当前页
     * @param name:per_page type:string require:0 default:10 other: desc:每页大小
     * @param name:status type:string require:0 default:1 other: desc:优惠券状态1可使用2已使用3已失效
     *
     * @return data:[]
     */
    public function getUserVoucher()
    {
        $uid = $this->arr['uid'];
        $status = $this->arr['status'] ?? 1;

        $current_page = $current_page ?? 1;
        $per_page = $per_page ?? 10;

        $list = UserRepository::instance()->userVouchers($uid, 'list', $status, $current_page, $per_page);
        return Fun::success($list);
    }

    /**
     * @title 用户余额
     * @description
     * @author jikesen
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:getUserBalance desc:用户余额
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other: desc:用户id
     *
     * @return data:[]
     */
    public function getUserBalance()
    {
        $uid = $this->arr['uid'];

        $list = UserRepository::instance()->userBalance($uid);
        $wallet['uid'] = $list['data']['uid'];
        $wallet['recharge_balance'] = sprintf("%.2f", $list['data']['recharge_balance'] / config('convert_unit'));
        $wallet['withdraw_balance'] = sprintf("%.2f", $list['data']['withdraw_balance'] / config('convert_unit'));
        $wallet['frozen_balance'] = sprintf("%.2f", $list['data']['frozen_balance'] / config('convert_unit'));
        $wallet['total_balance'] = sprintf("%.2f", $wallet['recharge_balance'] + $wallet['withdraw_balance']);

        if ($list['code'] == 'success') {
            return Fun::success($wallet);
        }
        return Fun::error($list['msg']);

    }

    /**
     * @title 用户交易明细
     * @description
     * @author jikesen
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:getUserExpenceLog desc:用户交易明细
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other: desc:用户id
     * @param name:current_page type:string require:0 default:1 other: desc:当前页
     * @param name:per_page type:string require:0 default:10 other: desc:每页大小
     *
     * @return data:[]
     */
    public function getUserExpenceLog()
    {
        $uid = $this->arr['uid'];

        $current_page = $this->arr['current_page'] ?? 1;

        $per_page = $this->arr['per_page'] ?? 10;

        $list = UserRepository::instance()->userExpenceLog($uid, $current_page, $per_page);

        return Fun::success($list);
    }

    /**
     * @title 用户提现
     * @description
     * @author jikesn
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     *
     * @param name:command type:string require:1 default:withdraw other: desc:
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other: desc:用户id
     * @param name:zfbAccount type:string require:1 default: other: desc:用户支付宝账户
     * @param name:realName type:string require:1 default: other: desc:用户真实姓名
     * @param name:amount type:int require:1 default: other: desc:提现金额 单位元
     *
     * @return name:data
     */
    public function withdraw()
    {
        $param = $this->arr;

        //用户禁止提现
        if(!User::get(['uid' => $param['uid'],'is_withdraw' => 0])){
            return Fun::error('500003');
        }

        $res = UserBalanceRespository::instance()->withdraw($param['uid'], $param['amount'], $param['zfbAccount'], $param['realName']);
        if ($res['code'] == 'fail') {
            return Fun::error('500002', $res['msg']);
        }
        return Fun::success('', '提现请求已申请');

    }

    /**
     * @title 用户退款
     * @description
     * @author jikesn
     * @url /api/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     *
     * @param name:command type:string require:1 default:withdraw other: desc:
     * @param name:token type:string require:1 default: other: desc:token
     * @param name:uid type:string require:1 default: other: desc:用户id
     * @param name:zfbAccount type:string require:1 default: other: desc:用户支付宝账户
     * @param name:realName type:string require:1 default: other: desc:用户真实姓名
     * @param name:amount type:int require:1 default: other: desc:提现金额 单位元
     *
     * @return name:data
     */
    public function refund()
    {

    }
}